package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.common.exception.BusinessException;
import com.demo.mapper.CoursePlanMapper;
import com.demo.pojo.dto.CoursePlanListDTO;
import com.demo.pojo.entity.CoursePlan;
import com.demo.service.CoursePlanService;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class CoursePlanServiceImpl extends ServiceImpl<CoursePlanMapper, CoursePlan>
        implements CoursePlanService {

    private final CoursePlanMapper coursePlanMapper;

    public CoursePlanServiceImpl(CoursePlanMapper coursePlanMapper) {
        this.coursePlanMapper = coursePlanMapper;
    }

    @Override
    public CoursePlan selectById(Long id) {
        CoursePlan cp = coursePlanMapper.selectById(id);
        if (cp == null) {
            throw new BusinessException("没有此课程安排");
        }
        return cp;
    }

    @Override
    public void saveCoursePlan(CoursePlan coursePlan) {
        coursePlanMapper.insert(coursePlan);
    }

    @Override
    public void updateCoursePlan(CoursePlan coursePlan) {
        if (coursePlan.getCpId() == null || coursePlanMapper.selectById(coursePlan.getCpId()) == null) {
            throw new BusinessException("没有此课程安排");
        }
        coursePlanMapper.updateById(coursePlan);
    }

    @Override
    public Map<String, Object> listPage(CoursePlanListDTO dto) {
        Page<CoursePlan> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<CoursePlan> qw = new LambdaQueryWrapper<CoursePlan>()
                .eq(StringUtils.isNotBlank(dto.getCpCourseId()), CoursePlan::getCpCourseId, dto.getCpCourseId())
                .eq(dto.getCpClassId() != null && dto.getCpClassId() != -1, CoursePlan::getCpClassId, dto.getCpClassId())
                .eq(dto.getCpTeacherId() != null && dto.getCpTeacherId() != -1, CoursePlan::getCpTeacherId, dto.getCpTeacherId())
                .eq(StringUtils.isNotBlank(dto.getCpRoomId()), CoursePlan::getCpRoomId, dto.getCpRoomId())
                .eq(dto.getCpWeekday() != null && dto.getCpWeekday() != -1, CoursePlan::getCpWeekday, dto.getCpWeekday())
                .ge(dto.getCpStartTime() != null, CoursePlan::getCpStartTime, dto.getCpStartTime())
                .le(dto.getCpEndTime() != null, CoursePlan::getCpEndTime, dto.getCpEndTime());

        Page<CoursePlan> pageResult = coursePlanMapper.selectPage(page, qw);
        return Map.of(
                "records", pageResult.getRecords(),
                "total", pageResult.getTotal(),
                "current", pageResult.getCurrent()
        );
    }
}


